package com.atguigu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.GmallConfig;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @className: DimUtil
 * @author: LinCong
 * @description:
 * @date: 2023/2/14 21:02
 * @version: 1.0
 */
public class DimUtil {

    public static JSONObject getDimInfo(Connection connection,String tableName,String key) throws Exception {
//        先查询redis
        Jedis jedis = JedisUtil.getJedis();
        String redisKey="DIM:"+tableName+":"+key;
        String dimJsonStr = jedis.get(redisKey);
        if (dimJsonStr!=null){
            jedis.expire(redisKey,24*60*6);
            jedis.close();
            return JSON.parseObject(dimJsonStr);
        }

//        redis中未查到才查phoenix
        String querySql="select * from "+ GmallConfig.HBASE_SCHEMA+"."+tableName+" where id ='"+key+"'";
        List<JSONObject> jsonObjects = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);
        JSONObject jsonObject = jsonObjects.get(0);
        jedis.set(redisKey,jsonObject.toString());
        jedis.expire(redisKey,24*60*60);
        jedis.close();

        return jsonObject;
    }

    public static void delDimInfo(String tableName,String key){
        Jedis jedis = JedisUtil.getJedis();
//        redis里面如果删除一个压根不存在的数据，没问题
        jedis.del("DIM:"+tableName+":"+key);
        jedis.close();
    }

    public static JSONObject getDimInfoNotCache(Connection connection,String tableName,String key) throws InvocationTargetException, SQLException, InstantiationException, IllegalAccessException {
        String querySql="select * from "+ GmallConfig.HBASE_SCHEMA+"."+tableName+" where id ='"+key+"'";

        List<JSONObject> jsonObjects = JdbcUtil.queryList(connection, querySql, JSONObject.class, false);

        return jsonObjects.get(0);
    }


    public static void main(String[] args) throws Exception {
        DruidDataSource dataSource = DruidDSUtil.createDataSource();
        DruidPooledConnection conn = dataSource.getConnection();

        long start1 = System.currentTimeMillis();
        JSONObject jsonObj1 = getDimInfo(conn, "DIM_BASE_TRADEMARK", "12");
        long end1 = System.currentTimeMillis();
        long start2 = System.currentTimeMillis();
        JSONObject jsonObj2 = getDimInfo(conn, "DIM_BASE_TRADEMARK", "12");
        long end2 = System.currentTimeMillis();
        System.out.println(jsonObj1);
        System.out.println(end1-start1);    //  161 164 159     176 138 213    94   105 108
        System.out.println(jsonObj2);       //  getDimInfoNotCache             getDimInfo
        System.out.println(end2-start2);    //                  9   9   10     1    1   0


        conn.close();
    }
}
